<?php
include_once("KillCommonModel.class.php");
include_once("Order.class.php");
include_once("Goods.class.php");

/**
 * 使用非阻塞的文件排他锁
 * Class ExclusiveFileSkill
 */
class ExclusiveFileSkill extends KillCommonModel{

    public function RunPurchase($id,$userId){
        $this->goodsIdBy=$id;
        $this->userId=$userId;
        if(!$this->run()){
            return false;
        }
    }

    private function run(){
        if(!$this->checkClassExists()){
            return false;
        }
        if(!$this->manage()){
            return false;
        }
    }

    /*
     * 处理相关抢购业务
     */
    private function manage(){
        $goodsObj=$this->goodsObj;
        $where=array($this->goodsId=>$this->goodsIdBy);
        $goodsInfo=$goodsObj->getRowGoodsInfo($where);

        if($goodsInfo==array() || !$goodsInfo){
            $this->error="商品不存在";
            return false;
        }
        $fp = fopen("lock.txt", "w+");  //对文件进行加锁
        if(!flock($fp,LOCK_EX | LOCK_NB)){
            $this->error="系统繁忙，请稍后再试";
            return  false;
        }
        //判断库存多少
        $sql="select  '.$this->counts.' from '.$this->goodsTable.' where '.$this->goodsId.'='.$this->goodsIdBy.' FOR UPDATE";
        $rs=mysql_query($sql,$this->conn);
        $row=mysql_fetch_assoc($rs);
        if($row[$this->counts]<=0){
            mysql_query("ROLLBACK");
            mysql_query("COMMIT");//事务提交即解锁
            $this->error="商品库存不足";
            return false;
        }
    }

    /*
     * 检查初始化配置是否存在
     * @return bool
     */
    private function checkClassExists(){

        if(!class_exists($this->goodsObj)){
            $this->error="商品表类不存在";
            return false;
        }
        $this->goodsObj=$goodsObj=new $this->goodsObj();
        if(!method_exists($goodsObj,"getRowGoodsInfo")){
            $this->error="商品表类中getRowGoodsInfo方法不存在";
            return false;
        }
        if(!method_exists($goodsObj,"updateCount")){
            $this->error="商品表类中updateCount方法不存在";
            return false;
        }

        if(!class_exists($this->oderObj)){
            $this->error="订单表类不存在";
            return false;
        }

        $this->oderObj=$orderObj=new $this->oderObj();
        if(!method_exists($orderObj,"createOrder")){
            $this->error="订单表类中createOrder方法不存在";
            return false;
        }
        return true;
    }
}